package com.webapp.controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.webapp.model.Circle;
import com.webapp.model.CircleModel;
import com.webapp.model.Person;
import com.webapp.model.User;

/**
 * Servlet implementation class CircleServlet
 */
public class CircleServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CircleServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// get session
		HttpSession session = request.getSession();
		
		// get the person object from session
		Person person = (Person)session.getAttribute("UserObject");
		String x = person.getType().toLowerCase();
		User myUser = myUser = (User) person;
		
		
		// get paramters from form in request object
		String fenceName = (String)request.getParameter("fenceNameTxt");
		String fenceType = (String)request.getParameter("fenceTypeTxt");
		
		// create and populate new circle
		Circle newCircle = new Circle();
		newCircle.setCircleName(fenceName);
		newCircle.setCircleOwner(myUser.getUserId());
		newCircle.setCircleType(fenceType);
		
		// get the circle model and send it off!
		CircleModel cm = new CircleModel();
		if(cm.createCircle(newCircle) == true) {
			
			// get the list of circle for user
			List circlesByOwner = cm.getCircleIdOwnerList(myUser.getUserId());
			
			// update circle in session and redirect
			session.setAttribute("Circles", circlesByOwner);
			RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/Circles.jsp?circle=created");
			dispatcher.forward(request, response);	
		} else {
			// redirect and say no go
			response.sendRedirect("Circles.jsp?circle=error");
		}
	}

}
